<template>
  <el-date-picker
    @change="handleChangeTime"
    v-model="defaultValue"
    type="datetimerange"
    :picker-options="pickerOptions"
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :clearable="true"
    align="right"
    :default-time="['00:00:00', '23:59:59']"
  ></el-date-picker>
</template>
<script>
const moment = require('moment')
export default {
  props: {
    timeBegin: {
      type: [String, Date],
      default: ''
    },
    timeEnd: {
      type: [String, Date],
      default: ''
    },
    isDefaultToday: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultValue: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  methods: {
    handleChangeTime(val) {
      if (val) {
        const startTimer = moment(val[0]).format('YYYY-MM-DD HH:mm:ss')
        const endTimer = moment(val[1]).format('YYYY-MM-DD HH:mm:ss')
        this.defaultValue = [startTimer, endTimer]
        this.$emit('update:timeBegin', startTimer)
        this.$emit('update:timeEnd', endTimer)
      } else {
        this.$emit('update:timeBegin', '')
        this.$emit('update:timeEnd', '')
      }
    }
  },
  mounted() {
    // 传指定时间
    if (this.timeBegin && this.timeEnd) {
      this.defaultValue = [this.timeBegin, this.timeEnd]
    } else if (this.isDefaultToday) {
      // 没传指定时间
      const monthTime = new Date().setTime(
        new Date().getTime() - 3600 * 1000 * 24 * 30
      )
      this.$set(
        this.defaultValue,
        0,
        moment(monthTime).format('YYYY-MM-DD HH:mm:ss')
      )
      this.$set(
        this.defaultValue,
        1,
        moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      )
      this.handleChangeTime(this.defaultValue)
    }
  }
}
</script>
